#!/usr/bin/env python
#-*-encoding:utf-8-*-
'''
Created on 2015年3月12日

@author: chenyongbing
'''
import sys,os,hashlib
#current_dir = os.path.dirname(__file__)
current_dir = os.path.split(os.path.realpath(__file__))[0]
sys.path.append(os.path.join(current_dir,'../../'))
from base.zhimind_datas import *
from base.retail_datas import *
from base.time_method import myTimeMethod
from base.PyExportFile import myExportFile


myZhimindDatas = ZhimindDatas()
myRetailDatas = RetailDatas()

import logging
class ExportHourData():
    u'''
        欧莱雅数据报表导出工具
    '''


    def __init__(self):
        '''
        Constructor
        '''
    def get_slist_between_st_et(self,st,et):
        u'''获取2个时间间的所有日期'''
        dlist = []
        count = 0
        nday = (datetime.date(int(st[:4]),int(st[5:7]),int(st[8:]))+ datetime.timedelta(-1)).strftime('%Y-%m-%d')
        while nday < et:
            nday = (datetime.date(int(st[:4]),int(st[5:7]),int(st[8:]))+ datetime.timedelta(count)).strftime('%Y-%m-%d')
            count+=1
            dlist.append(nday)
        return dlist
    
    
    def get_hour_flow_datas(self,comp_group=None,comp_id=None,groups=[],startTime=None,endTime=None):
        u'''rtype:1:入店量;2:客流量;3:路人量
        '''
        alldatas = []
        if startTime == None:
            startTime= datetime.date.today().strftime('%Y-%m-%d')
        if endTime == None:
            endTime = datetime.date.today().strftime('%Y-%m-%d')
        fields = [u'日期',u'星期',u'时间段',u'名称',u'门店',u'品牌',u'店铺编码',u'归属省份',u'归属城市',u'客流量',u'入店量',u'路过客流']
        alldatas.append(fields)
        if (comp_group!=None or comp_id!=None) and len(groups)==0:
            groups = myRetailDatas.get_groups_by_comp(comp_group=comp_group,comp_id=comp_id)
        if len(groups)==0:
            logging.warn('comp_group or  groups is required.')
        groupInfos = myRetailDatas.get_groups_info(groups=groups)
        cust_datas = myZhimindDatas.get_flow_by_hour(startTime=startTime, endTime=endTime, rtype=1, groups=groups)
        flow_datas = myZhimindDatas.get_flow_by_hour(startTime=startTime, endTime=endTime, rtype=2, groups=groups)
        
        days = self.get_slist_between_st_et(startTime, endTime)
        

        for group,groupInfo in groupInfos.iteritems():
            
            group_name = groupInfo['name']
            serial_number = groupInfo['serial_number']
            province = groupInfo['province']
            city = groupInfo['city']
            try:
                shop_name,shop_brand = group_name.split('-')
            except:
                shop_name = shop_brand=''
            for day in days:
                weekday = myTimeMethod.get_weekday(day)
                for hour in range(24):
                    try:
                        cust_count = cust_datas[group][day][hour]
                    except:
                        cust_count = '-'
                    try:
                        flow_count = flow_datas[group][day][hour]
                    except:
                        flow_count = '-'
                    if flow_count=='-':
                        walk_count = '-'
                    elif cust_count == '-':
                        walk_count = flow_count
                    else:
                        walk_count = flow_count - cust_count
                    hour_str = '0'*(2-len(str(hour)))+str(hour)+':00:00'
                    values = [day,weekday,hour_str,group_name,shop_name,shop_brand,serial_number,province,city,str(flow_count),str(cust_count),str(walk_count)]
                    alldatas.append(values)
        return alldatas
    

    def export_hour_flow_datas(self,rule='hour_flow_data_report',comp_group=[],comp_id=None,shop_group=None, startTime=None, endTime=None, export_file=''):
        datas = []
        if shop_group:
            groups = [shop_group]
        else:
            groups = []
        if re.search( 'hour_flow_data_report',rule):
            datas = self.get_hour_flow_datas(comp_group=comp_group, comp_id=comp_id,groups=groups, startTime=startTime, endTime=endTime)
        myExportFile.export_online_time(datas, export_file)
myExportLorealData = ExportHourData()      
if __name__ == '__main__':
    from localConfig import LocalConfig

    myLocalConfig = LocalConfig()
    

    import argparse,re,datetime,time
    parser = argparse.ArgumentParser(description='args')
    parser.add_argument('--startTime',metavar=u"starttime",default=None)
    parser.add_argument('--endTime',metavar=u"endtime",default=None)
    parser.add_argument('--rule',metavar=u"rule",default=None)
    parser.add_argument('--format',metavar=u"export file export",default='csv')
    parser.add_argument('--shop_group',metavar=u"shop groups",default=None)
    parser.add_argument('--comp_group',metavar=u"company groups",default=None)
    parser.add_argument('--comp_id',metavar=u"company id",default=None)
    args = parser.parse_args()
    
    startTime = args.startTime
    endTime = args.endTime
    rule = args.rule
    format = args.format
    shop_group = args.shop_group
    comp_group = args.comp_group
    comp_id = args.comp_id
    if startTime == None:
        startTime = datetime.date.today().strftime('%Y-%m-%d')
    if endTime == None:
        endTime = datetime.date.today().strftime('%Y-%m-%d')
    
    if  shop_group!=None:
        comp_group = None
        comp_id = None
        #file_name = myRetailDatas.get_comp_name(shop_group=shop_group).encode("utf-8")
        file_name = myRetailDatas.get_group_name(group=shop_group).encode("utf-8")
    elif 'comp_group' in myLocalConfig.rules[rule].keys() and 'comp_id' in myLocalConfig.rules[rule].keys():
        comp_group = myLocalConfig.rules[rule]['comp_group']
        comp_id = myLocalConfig.rules[rule]['comp_id']
        shop_group = None
        file_name = myRetailDatas.get_comp_name(shop_group=comp_group).encode("utf-8")
    elif comp_group!=None or comp_id!=None:
        if comp_group!=None:
            comp_id = myRetailDatas.get_comp_id(comp_group=comp_group)
        elif comp_id!=None:
            comp_group = myRetailDatas.get_comp_group(comp_id= comp_id)

        shop_group = None
        file_name = myRetailDatas.get_comp_name(shop_group=comp_group).encode("utf-8")
    
    export_file = myLocalConfig.rules[rule]['export_path'] +'/'+'%s小时报表(%s-%s).%s'%(file_name,re.sub('-','.',startTime),re.sub('-','.',endTime),format)
    myExportLorealData.export_hour_flow_datas(rule=rule,shop_group=shop_group,comp_group=comp_group,comp_id=comp_id, startTime=startTime, endTime=endTime, export_file=export_file)
        
    
    